package com.mj.listen3.链表;

public class _0_在双链表中删除倒数第K个节点 {
    public DoubleNode removeLastKthNode(DoubleNode head, int lastKth) {
        if (head == null || lastKth < 1) return head;
        DoubleNode cur = head;
        while (cur != null) {
            cur = cur.next;
            lastKth--;
        }

        if (lastKth == 0) {
            // 删除的是头节点
            head = head.next;
            head.pre = null;
        }

        if (lastKth < 0) {
            cur = head;
            while (++lastKth != 0) {
                cur = cur.next;
            }

            // lastKth = 0。此时的cur就是要删除节点的前一个节点
            cur.next = cur.next.next;
            if (cur.next.next != null) {
                // 往前指向也改变
                cur.next.next.pre = cur;
            }
        }

        // lastKth > 0 说明 lastKth 超出了链表的长度了

        return head;
    }
}
